package job

import (
	"scheduler/dal"
	"strings"
	"time"
	//	"encoding/json"
	json "github.com/json-iterator/go"
	log "github.com/sirupsen/logrus"
)

func Time2Duration(t time.Time) time.Duration {
	return t.Sub(time.Now())
}

func DurationToTime(d time.Duration) time.Time {
	log.Debug(time.Unix(int64(d), 0))
	return time.Unix(int64(d), 0)
}

func StringToDuration(s string) (time.Duration, error) {
	t, err := time.Parse("yyyy-MM-dd HH:mm:ss", s)
	if nil != err {
		return 0, err
	}

	return Time2Duration(t), nil
}

func FullURL(addr, path string, params map[string]string) string {
	url := addr + path + "?"
	for k, v := range params {
		url += k + "=" + v + "&"
	}
	return strings.TrimSuffix(url, "&")
}

func StringToMap(s string) (map[string]string, error) {
	m := make(map[string]string)
	err := json.UnmarshalFromString(s, &m)
	if nil != err {
		log.Errorln(err)
		return nil, err
	}

	return m, nil
}

func MapToString(m map[string]string) (string, error) {
	return json.MarshalToString(m)
}

func ModelJobToJob(j *dal.Job) *Job {
	var job Job
	job.ID = j.ID

	var tasks = []*Task{}
	for _, t := range j.Tasks {
		tasks = append(tasks, ModelTaskToTask(t))
	}

	job.Tasks = make(map[string]*Task, len(j.Tasks))
	for _, t := range tasks {
		job.Tasks[t.ID] = t
	}

	return &job
}

func ModelTaskToTask(t *dal.Task) *Task {
	var task Task
	task.Action = &Action{}
	task.Action.Addr = t.Addr
	task.Action.Path = t.Path
	task.Action.Body = t.Body
	task.ID = t.ID
	task.Retry = t.Retry
	task.StartAt = DurationToTime(time.Duration(t.StartAt))

	return &task
}
